<template>
  <n-modal
    v-model:show="showModal"
    preset="card"
    :title="title"
    :show-icon="false"
    class="w-800px"
  >
    <!-- 创建和编辑区域 -->
    <mycard v-if="editType === 'add' || editType === 'edit'">
     <n-form ref="formRef" :model="formValue" :rules="rules" :label-width="120"
              label-placement="left" class="mt-2">
        <n-grid x-gap="12">
          <n-gi :span="24">
            <n-form-item label="菜单名称:" path="name">
              <n-input v-model:value="formValue.name" @keydown.enter.prevent
                       placeholder="请输入菜单名称" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="父级菜单:" path="parent">
              <n-cascader
                  v-model:value="formValue['parent']"
                  placeholder="请选择"
                  :options="parentoptions"
                  value-field='id'
                  label-field='name'
                  remote
                  :show-path="false"
                  clearable
              />
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="菜单排序:" path="sort">
              <n-input v-model:value="formValue['sort']" placeholder="请输入排序" clearable/>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="菜单分类:" path="fenlei">
              <n-radio-group v-model:value="formValue.fenlei" name="radiogroup5">
                <n-space>
                  <n-radio :value="1">
                    内部路由
                  </n-radio>
                  <n-radio :value="2">
                    外联
                  </n-radio>
                  <n-radio :value="3">
                    目录
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei===1">
            <n-form-item label="路由地址:" path="route">
              <n-input v-model:value="formValue.route" @keydown.enter.prevent
                       placeholder="请输入路由地址" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei===1">
            <n-form-item label="组件路径:" path="routePath">
              <n-input v-model:value="formValue.routePath" @keydown.enter.prevent
                       placeholder="请输入组件路径" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei===1">
            <n-form-item label="组件name:" path="routerKey">
              <n-input v-model:value="formValue.routerKey" @keydown.enter.prevent
                       placeholder="请输入组件name" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="外链url:" path="url" v-if="formValue.fenlei===2">
              <n-input v-model:value="formValue.url" @keydown.enter.prevent
                       placeholder="请输入外链url" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="是否缓存:" path="cache">
              <n-radio-group v-model:value="formValue.cache" name="radiogroup4">
                <n-space>
                  <n-radio :value="1">
                    是
                  </n-radio>
                  <n-radio :value="2">
                    否
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="状态:" path="status">
              <n-radio-group v-model:value="formValue.status" name="radiogroup3">
                <n-space>
                  <n-radio :value="1">
                    启用
                  </n-radio>
                  <n-radio :value="2">
                    停用
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="侧边显示:" path="show">
              <n-radio-group v-model:value="formValue.show" name="radiogroup2">
                <n-space>
                  <n-radio :value="1">
                    是
                  </n-radio>
                  <n-radio :value="2">
                    否
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="是否打开新页面:" path="blank">
              <n-radio-group v-model:value="formValue.blank" name="radiogroup1">
                <n-space>
                  <n-radio :value="2">
                    是
                  </n-radio>
                  <n-radio :value="1">
                    否
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="描述:" path="desc">
              <n-input v-model:value="formValue.desc" @keydown.enter.prevent
                       type="textarea"
                       placeholder="请输入描述" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
        </n-grid>
      </n-form>
    </mycard>
    <!-- 回显区域 -->
    <mycard v-if="editType === 'view'">
      <descriptions :infoList='_infoList'></descriptions>
    </mycard>

    <!-- 交互成功区域 -->
    <mycard v-if="editType === 'success'">
      <n-result status="success" title="成功" :description="resultText">
      </n-result>
    </mycard>
    <!-- 交互失败区域 -->
    <mycard v-if="editType === 'error'">
      <n-result status="error" title="错误" :description="resultText">
      </n-result>
    </mycard>
    <template #action>
      <div class="w-full flex justify-end items-center">
        <n-button class="mx-1" v-if="editType === 'error'" @click="getreturn">返回</n-button>
        <n-button class="mx-1" @click="handleClose">关闭</n-button>
        <n-button
          class="mx-1"
          v-if="editType === 'add' || editType === 'edit'"
          type="primary"
          @click="handleSave"
          >确定</n-button
        >
      </div>
    </template>
  </n-modal>
</template>


<script setup name="Edit" lang="ts">
import { openAndClose } from '../../../hooks/useEdit'
import guiling from '../../../util/guiling'
import { ref, defineEmits, defineExpose, computed,h } from 'vue'
import {FormItemRule, NTag} from "naive-ui"
import zhengze from '../../../util/zhengze'
const formRef = ref<any>(null)   // 表单组件
const formValue = ref<any>({})   // 表单数据
const checknum=( rule: FormItemRule,  value: string)=>{
  const regx = zhengze.isNum
  if(!value) {
    return true
  }else if(value.length > 10){
    return new Error("请输入长度10位以内的数字")
  }else if(!regx.test(value)){
    return new Error("请输入数字")
  }else{
    return true
  }
}
const checkUrl=( rule: FormItemRule,  value: string)=>{
  const regx = /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/
  if(!value){
    return true
  }else if(!regx.test(value)){
    return new Error("请输入正确的url")
  }else{
    return true
  }
}
const rules=ref({
  name:[{required:true,message:"请输入菜单的名称",  trigger: ['input', 'change', 'blur'],},{
    max: 200,
    min: 2,
    message: '请输入2-200位的字符',
    trigger: ['input', 'change', 'blur'],
  },],
  parent:[],
  sort:[{required:true,message:"请输入菜单的排序",  trigger: ['input', 'change', 'blur'],},{validator:checknum,trigger: ['input', 'change', 'blur']}],
  fenlei:[{type:"number",required:true,message:"请选择分类",trigger: ['input', 'change', 'blur']}],
  route:[{required:true,message:"请输入路由的地址",  trigger: ['input', 'change', 'blur'],},{
    max: 200,
    min: 2,
    message: '请输入2-200位的字符',
    trigger: ['input', 'change', 'blur'],
  },],
  routePath:[{required:true,message:"请输入路由的组件路径",  trigger: ['input', 'change', 'blur'],},{
    max: 200,
    min: 2,
    message: '请输入2-200位的字符',
    trigger: ['input', 'change', 'blur'],
  },],
  routerKey:[{required:true,message:"请输入路由的name属性",  trigger: ['input', 'change', 'blur'],},{
    max: 200,
    min: 2,
    message: '请输入2-200位的字符',
    trigger: ['input', 'change', 'blur'],
  },],
  url:[{required:true,message:"请输入外链地址",  trigger: ['input', 'change', 'blur'],},{validator:checkUrl,  trigger: ['input', 'change', 'blur'],},],
  cache:[{type:"number",required:true,message:"请选择是否缓存",trigger: ['input', 'change', 'blur']}],
  status:[{type:"number",required:true,message:"请选择是否启用",trigger: ['input', 'change', 'blur']}],
  blank:[{type:"number",required:true,message:"请选择是否打开新页面",trigger: ['input', 'change', 'blur']}],
  show:[{type:"number",required:true,message:"请选择是否侧边显示",trigger: ['input', 'change', 'blur']}],
})         // 表单的校验规则
const parentoptions=ref([]) // 备选的父级数据
const emit = defineEmits(["close"])
// 自定义重置组件的方法
const reset = () => {
  formValue.value = guiling(formValue.value)
  emit("close",)
}
// 自定义初始化需要执行的方法
const chushihua = (data: any,edittype:"add"|"edit"|"view"|"") => {
  if (data) {
    formValue.value = data
  }
  if(edittype!=="view") {
    gettreeDatefunc()
  }
}
// 从钩子中结构出需要的函数和属性
const {
  showModal,
  editType,
  resultText,
  init,
  handleClose,
  getsuccess,
  getfaild,
  title,http,message,
} = openAndClose(chushihua, reset)

// 点击确定
const handleSave = () => {
  console.log(formRef.value,"是什么啊")
  if (formValue.value.id) {
    formRef.value?.validate((error:any)=>{
      if(!error){
        updatefunc(formValue.value)
      }else{
        return false
      }
    })
  } else {
    formRef.value?.validate((error:any)=>{
      if(!error){
        createfunc(formValue.value)
      }else{
        return false
      }
    })
  }
}

const createfunc = (data: any) => {
  http.menuadd(data).then((res:any)=>{
    if(res.data.code==0){
      getsuccess("创建菜单成功")
    }else{
      getfaild(res.data.error || res.data.msg)
    }
  }).catch(err=>{
    getfaild(err || "创建菜单失败")
  })
}

const updatefunc = (data: any) => {
  http.menuupdate(data,formValue.value.id).then((res:any)=>{
    if(res.data.code==0){
      getsuccess("修改菜单成功")
    }else{
      getfaild(res.data.error || res.data.msg)
    }
  }).catch(err=>{
    getfaild(err || "修改菜单失败")
  })
}

// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = 'edit'
  } else {
    editType.value = 'add'
  }
  resultText.value = ''
}

// 获取菜单的属性数据
const gettreeDatefunc=()=>{
  http.menutree({},).then((res:any)=>{
    if(res.data.code===0){
      parentoptions.value = res.data.items
    }else{
      message.error(res.data.msg || "获取全部菜单失败")
    }
  }).catch(err=>{
    message.error(err || "获取全部菜单失败")
  })
}

const infoList = ref([
  {label:"菜单名称",key:"name",},
  {label: "排序", key: "sort", },
  {label: "分类", key: "fenlei", render: (data:any,)=>{
      return data==1?"内部路由":data==2?"外链":data==3?"目录":""
    }},
  {label: "上级菜单", key: "parent", render: (rowDate:any,)=>{
      return rowDate ? rowDate.name : ""
    }},
  {label: "是否缓存", key: "cache",render: (rowDate:any,)=>{
      return rowDate==1?"是":"否"
    } },
  {label: "启用", key: "status",render: (rowDate:any)=>{
      return rowDate==1?"是":"否"
    } },
  {label: "侧边显示", key: "show",render: (rowDate:any,)=>{
      return rowDate==1?"是":"否"
    } },
  {label: "打开新页面", key: "blank", render: (rowDate:any,)=>{
      return rowDate==1?"否":"是"
    }},
  {label:"描述",key:"desc"},
  {label:"创建时间",key:"createdTime",render: (time:string)=>{
      return new Date().toMyString(time)
    }},
  {label:"更新时间",key:"changeTime",render: (time:string)=>{
      return new Date().toMyString(time)
    }},
])
const _infoList=computed(()=>{
  return infoList.value.map((item:any)=>{
    return {...item,value: item.render?item.render(formValue.value[item.key]):formValue.value[item.key]}
  })
})




// 抛出属性和方法
defineExpose({ init, handleClose })

</script>

<style scoped>
</style>
